﻿from fastapi import FastAPI, File, UploadFile, HTTPException,Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import os

img_dir = '/mnt/c/Users/10485/Desktop/image_waterfall'

app = FastAPI()

# 配置静态文件路径，用于存储上传的图片
app.mount("/static", StaticFiles(directory="static"), name="static")

# 使用Jinja2Templates来渲染HTML模板
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
def read_root(request: Request):
    filenames = os.listdir("static")
    file_info_list = [(file, os.path.getsize(os.path.join("static", file))) for file in filenames]
    sorted_files = sorted(file_info_list, key=lambda x: x[1])
    sorted_file_names = [file[0] for file in sorted_files]
    return templates.TemplateResponse("index.html", {"request": request,"filenames": sorted_file_names})


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    # 保存上传的文件到static目录
    with open(os.path.join("static", file.filename), "wb") as f:
        f.write(file.file.read())
    return {"filename": file.filename}
